package com.huatai.vba.execute.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONUtils;
import com.huatai.vba.common.utils.FileUtils;
import com.huatai.vba.common.utils.ListUtils;
import com.huatai.vba.dal.jdbc.DBUtils;
import com.huatai.vba.dal.model.VbaFileHandler;
import com.huatai.vba.dal.model.VbaFileHandlerRecord;

@Service(value = "createFileExecuteService")
public class CreateFileExecuteServiceImpl extends ExecuteService {

	@SuppressWarnings("unchecked")
	@Override
	public VbaFileHandlerRecord handler(VbaFileHandler handler) throws Exception {
		String url = handler.getHandlerSource();
		Map<String, String> map = (Map<String, String>) JSONUtils.parse(handler.getHandlerProperties());
		String sql = handler.getHandlerSql();
		List<String> files = (List<String>) JSONUtils.parse(handler.getHandlerFileRegular());
		List<Map<String, Object>> result = DBUtils.executeQuery(url, map.get("user"), map.get("password"), sql);
		if (handler.getHandlerFileRegular().indexOf(".txt") > 0)
			createTxtFile(result, handler.getHandlerDestination(), files.get(0));
		if (handler.getHandlerFileRegular().indexOf(".") < 0)
			createTxtFile(result, handler.getHandlerDestination(), files.get(0));
		VbaFileHandlerRecord record = new VbaFileHandlerRecord();
		record.setFileNames(files.get(0));
		record.setFileNum(1);
		return record;
	}

	private void createTxtFile(List<Map<String, Object>> result, String destination, String fileName) throws Exception {
		List<String> contents = new ArrayList<String>();
		if (ListUtils.isNotEmpty(result)) {
			for (Map<String, Object> m : result) {
				String field = m.keySet().iterator().next();
				contents.add((String) m.get(field));
			}

			FileUtils.writeLines(destination, fileName, contents);
		}
	}

}
